package com.pig4cloud.pigx.common.customize.feign;

import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * feign全局异常处理类
 *
 * @since 2022/9/20 13:54
 */
@Component
@AllArgsConstructor
public class CommonFeignErrorDecoder implements ErrorDecoder {

	private final CommonUtil commonUtil;

	/**
	 * 处理异常
	 *
	 * @param methodKey feign接口及方法名
	 * @param response  响应体
	 * @return {@link Exception}
	 * @since 2022/9/20 14:42
	 */
	@Override
	public Exception decode(final String methodKey, final Response response) {
		try {
			// 获取返回体，转换为对象
			String message = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
			R<?> r = commonUtil.parseJson(message, R.class);

			// 根据对象返回的值，重新抛出异常
			return new RuntimeException(r.getMsg());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
